17. Exercise: Lifecycle Observation
ANDK L4 33 Lifecycle Observation SC V2
Now it’s your turn to complete this exercise yourself.
You're going to use Lifecycle Observation to start and stop the timer.
**1. Make DessertTimer a LifecycleObserver: **
In order to achieve this, DessertTimer should implement a LifecycleObserver, take in a Lifecycle as a parameter and establish observer relationship in init block.
class DessertTimer(lifecycle: Lifecycle) : LifecycleObserver {
init {
lifecycle.addObserver(this)
}
}
2. Annotate startTimer and stopTimer with @OnLifecycleEvent and the correct event:
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun startTimer() {...}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stopTimer() {...}
3. Pass in 'this' MainActivity's lifecycle so that it is observed:
dessertTimer = DessertTimer(this.lifecycle)
If you want to start at this step, you can download this exercise code from: Step.04-Exercise-Add-the-lifecycle-library.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here Step.04-Solution-Add-the-lifecycle-library or using this git diff
Task Description:
Check the steps below as you implement them to complete this exercise.
Task Feedback:
Great work!
Solution: Step.04-Solution-Add-the-lifecycle-library or using this git diff